<?php

namespace app\common\service;
use app\common\model\system\Node;
use app\common\model\system\RoleNode;
use app\common\model\system\User;
use think\facade\Db;

class AuthService
{
    protected $user_id;
    protected $user;
    protected $nodeList;
    protected $userNode;
    public function __construct($user_id = 0)
    {
        $this->user_id =$user_id;
        $this->user = $this->getUser();
        $this->nodeList = $this->getNodeList();
        $this->userNode = $this->getUserNode();
    }
    public function checkNode($node = ''){
        if($this->user_id == 1){
            return true;
        }
        if($this->config['auth_on'] == false){
            return true;
        }
        if(empty($node)){
            $node = $this->getCurrentNode();
        }
        if(!isset($this->nodeList[$node])){
            return false;
        }
        if($this->nodeList[$node]['is_auth'] == 0){
            return true;
        }
        if(empty($this->user) || $this->user['status'] != 1 || empty($this->user['auth_ids'])){
            return false;
        }
        if(in_array($node,$this->userNode)){
            return true;
        }
        return false;
    }
    public function getUser(){
       return app(User::class)->getInfo($this->user_id);
    }
    /**
     * 获取所有节点信息
     */
    public function getNodeList(){
        return app(Node::class)->getList();
    }
    //获取用户节点
    public function getUserNode(){
        $nodeList = [];
        if($this->user_id == 1){
            $nodeList = $this->getNodeList();
        }
        if(!empty($this->user) && !empty($this->user['role_ids'])){
            $role_nodes = app(RoleNode::class)->getList([['role_id','in',$this->user['role_ids']]]);
            $node_ids = array_column($role_nodes,'node_id');
            $nodes = app(Node::class)->getList([['id','in',$node_ids]]);
            $nodeList =array_column($nodes,'node');
        }
        return $nodeList;
    }
    public function getCurrentNode(){
        $node = request()->controller().'/'.request()->action();
        return $node;
    }
    private function parseNodeStr($node){
        $array = explode('/',$node);
        foreach ($array as $key =>$val){
            if($key == 0){
                $val =explode('.',$val);

            }
        }

    }
}